<%@ page language="java" pageEncoding="UTF-8" %>
<!doctype html>
<html lang="zh-CN">
<head>
    <%@include file="/WEB-INF/views/commons/common.jsp" %>
    <link rel="stylesheet" type="text/css" href="${base_href}/static/ui-frame/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css"
          href="${base_href}/static/ui-frame/bootstrap-dialog3/css/bootstrap-dialog.css">
    <link rel="stylesheet" type="text/css"
          href="${base_href}/static/ui-frame/validation-engine/validationEngine.jquery.css">
    <link rel="stylesheet" type="text/css"
          href="${base_href}/static/ui-frame/jquery-easyui/1.4.3/themes/metro/easyui.css">
    <link rel="stylesheet" type="text/css"
          href="${base_href}/static/ui-frame/font-awesome/4.3.0/css/font-awesome.min.css">

    <link rel="stylesheet" type="text/css" href="${base_href}/static/ui-frame/webuploader/0.1.5/webuploader.css">
    <link rel="stylesheet" type="text/css" href="${base_href}/static/ui-frame/viewer/viewer.css">
    <link rel="stylesheet" type="text/css" href="${base_href}/static/ui-frame/ztree-v3/css/zTreeStyle/zTreeStyle.css">
    <link rel="stylesheet" type="text/css" href="${base_href}/static/css/search-theme.css">
    <link rel="stylesheet" type="text/css" href="${base_href}/static/css/form-theme.css">

    <title>创建试卷</title>
</head>
<body data-spy="scroll" data-target="#myScrollspy" data-offset="350">


<div class="main-wrap">

    <!-- 工具条 start-->
    <div class="container-fluid form-body-header">
        <div class="container">
            <div class="row tool-bar">
                <div class="col-xs-12">
                    <button type="button" class="btn btn-sm tool-btn" id="saveBtn">保存为草稿</button>
                    <button type="button" class="btn btn-sm tool-btn" id="submitBtn">创建试卷</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 工具条 end-->

    <!-- 表单 start-->
    <div class="container-fluid">
        <form id="form">

            <input type="hidden" name="id" value="${form.id }"/>

            <div class="container form-body-div">
                <div class="row text-center title-body" id="baseinfo">
                    试卷详细信息<br/>
                </div>

                <div class="row pannel-title">
                    <span>基本信息</span> <a href="javascript:void(0);" class="hide-next-btn">收起</a>
                </div>
                <div class="row pannel-body">
                    <table class="form-table">
                        <tr>
                            <th class="col-xs-2 ">创建人</th>
                            <td class="col-xs-4" colspan="2">
                                ${form.createUserName}
                            </td>
                            <th class="col-xs-2 ">创建时间</th>
                            <td class="col-xs-4" colspan="2">
                                <fmt:formatDate value="${form.createTime}" type="both" pattern="yyyy-MM-dd HH:mm"/>
                            </td>
                        </tr>
                        <tr>
                            <th class="col-xs-2 ">试卷名称</th>
                            <td class="col-xs-4" colspan="5">
                                <input type="text" class="form-control validate[required,maxSize[50]]" name="paperName"
                                       value="${form.paperName}"/>
                            </td>

                        </tr>
                    </table>
                </div>

                <div class="row pannel-title">
                    <span>检索条件</span> <a href="javascript:void(0);" class="hide-next-btn">收起</a>
                </div>
                <div class="row pannel-body">
                    <div>
                        <ul id="tabMenu">
                            <li class="active"><a href="#A" data-toggle="tab">
                                大纲搜索 </a>
                            </li>
                            <li><a href="#B" data-toggle="tab">
                                题目搜索</a>
                            </li>
                            <li><a href="#C" data-toggle="tab">
                                科目章节搜索</a>
                            </li>
                        </ul>

                        <div id="myTabContent" class="tab-content">
                            <div class="tab-pane fade in active" id="A">
                                <div title="" class="panel-body layout-body"
                                     style="width:50%; float:left; overflow:auto; height:480px; border:none; padding: 2px 5px 5px;">
                                    <ul id="treeDemo" class="ztree" style="width: 100%;"></ul>
                                </div>
                                <div class="tree_s_box" style="width: 50%; float:left;overflow: auto; height: 480px;">
                                    <ul class="treeSelected" id="treeDemoSelected">
                                    </ul>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="B">
                                <iframe style="width: 100%; height: 480px; border: 0px;"
                                        src="${base_href}/questionList/listSearchPage.html"></iframe>
                            </div>

                            <div class="tab-pane fade" id="C">
                                <p>此功能尚未开放</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row pannel-title">
                    <span>题目信息</span> <a href="javascript:void(0);" class="hide-next-btn">收起</a>
                </div>
                <div class="row pannel-body">
                    <table class="form-table">
                        <tr id="quesTitle" data-index="${form.paperDetails.size() }">
                            <th class="col-xs-1 ">
                                题目编号
                            </th>
                            <th class="col-xs-7 ">
                                题目信息
                            </th>
                            <th class="col-xs-1 ">
                                设置分数
                            </th>
                            <th class="col-xs-3 ">
                                操作
                            </th>
                        </tr>
                        <c:forEach items="${form.paperDetails}" var="detail" varStatus="status">
                            <tr class="quesDetail" data-related="${detail.relationCode}">
                                <td class="col-xs-1 ">
                                    <input type="hidden" class="quesId" name="paperDetails[${status.index }].quesId"
                                           value="${detail.quesId}">
                                    <input type="hidden" name="paperDetails[${status.index }].paperId"
                                           value="${detail.paperId}">
                                    第 <span class="quesIndex">${status.index+1}</span> 题<br>
                                        ${detail.quesCode}<br>
                                        ${detail.quesTypeValue}
                                </td>
                                <td class="col-xs-7 ">
                                    <c:choose>
                                        <c:when test="${detail.stem eq '' || detail.stem eq null}">
                                            &nbsp;&nbsp;&nbsp;&nbsp;题目：${detail.question}
                                        </c:when>
                                        <c:otherwise>
                                            &nbsp;&nbsp;&nbsp;&nbsp;主题干：${detail.question}<br>
                                            &nbsp;&nbsp;&nbsp;&nbsp;分题干：${detail.stem}
                                        </c:otherwise>
                                    </c:choose>
                                    <c:forEach items="${detail.options }" var="option" varStatus="optionStatus">
                                        <div class="checkbox checkbox-success">
                                            <label for="myAnswer['${status.index}']['${optionStatus.index }']">
                                                    ${answers[optionStatus.index] }：${option}
                                            </label>
                                        </div>
                                    </c:forEach>
                                    &nbsp;&nbsp;&nbsp;&nbsp;正确答案：${detail.answer }<br>
                                    &nbsp;&nbsp;&nbsp;&nbsp;解析：${detail.analysis }<br>
                                </td>
                                <td class="col-xs-1 ">
                                    <input type="text" class="form-control validate[required]"
                                           name="paperDetails[${status.index }].score" value="${detail.score}">
                                </td>
                                <td class="col-xs-3 ">
                                    <button type="button" class="btn btn-danger delete">删除</button>
                                    <button type="button" class="btn btn-info upper">上移</button>
                                    <button type="button" class="btn btn-info down">下移</button>
                                </td>
                            </tr>
                        </c:forEach>
                    </table>
                </div>
            </div>
        </form>
    </div>
    <!-- 表单 end-->

</div>
<script type="text/javascript" src="${base_href}/static/ui-frame/jquery/1.11.3/jquery.js"></script>
<script type="text/javascript" src="${base_href}/static/ui-frame/bootstrap/3.3.5/js/bootstrap.js"></script>
<script type="text/javascript" src="${base_href}/static/ui-frame/bootstrap-dialog3/js/bootstrap-dialog.js"></script>
<script type="text/javascript"
        src="${base_href}/static/ui-frame/validation-engine/jquery.validationEngine-zh_CN.js"></script>
<script type="text/javascript" src="${base_href}/static/ui-frame/validation-engine/jquery.validationEngine.js"></script>
<script type="text/javascript" src="${base_href}/static/ui-frame/My97DatePicker/WdatePicker.js"></script>

<script type="text/javascript" src="${base_href}/static/ui-frame/ztree-v3/js/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript" src="${base_href}/static/support/paper/outline-tree.js"></script>
<script type="text/javascript" src="${base_href}/static/ui-frame/layer/layer.js"></script>

<script type="text/javascript">
    $(function () {
        $('#form').validationEngine('attach', {
            maxErrorsPerField: 1,
            scroll: false,
            validationEventTrigger: "keyup blur change focus",
            ValidateNoneVisibleFields: true,//验证隐藏域
            promptPosition: "topRight" //验证弹出框的位置，topRight,topLeft,bottomRight,bottomLeft,centerRight,centerLeft,inline
        });

        $("#saveBtn").click(function () {
            if ($('#form').validationEngine('validate')) {
                return $.post(basePath + "/paper/savePaper.json", $("#form").serialize(), function () {
                    BootstrapDialog.show({
                        title: "提示框",
                        message: "保存成功",
                        buttons: [{
                            label: "确认",
                            action: function (dialog) {
                                dialog.close();
                            }
                        }]
                    });
                }, 'json');
            }
        });
        $("#submitBtn").click(function () {
            if ($(".quesDetail").length == 0) {
                BootstrapDialog.show({
                    title: "提示框",
                    message: "请先添加题目",
                    buttons: [{
                        label: "确认",
                        action: function (dialog) {
                            dialog.close();
                        }
                    }]
                });
                return;
            }
            $('a.hide-next-btn-show').each(function (i, val) {
                $(this).click();
            });
            if ($('#form').validationEngine('validate')) {
                return $.post(basePath + "/paper/submitPaper.json", $("#form").serialize(), function () {
                    BootstrapDialog.show({
                        title: "提示框",
                        message: "创建成功",
                        buttons: [{
                            label: "确认",
                            action: function (dialog) {
                                window.close();
                            }
                        }]
                    });
                }, 'json');
            }
        });

        //初始化大纲
        OutlineApp.Tree.selectOutLine({
            multi: false,
            selectData: new Array(),
            currentTreeId: "treeDemo",
            selectType: "checkbox"
        });

        $("table ").on('click', ".delete", function () {
            var $tr = $(this).parent().parent();
            var relatedId = $tr.attr("data-related");
            if (relatedId != null && relatedId != "" && relatedId != undefined) {
                $("tr[data-related='" + relatedId + "']").each(function () {
                    $(this).nextAll().each(function () {
                        var index = $(this).find(".quesIndex").text();
                        $(this).find(".quesIndex").text(Number(index) - 1);
                    })
                    $(this).remove();
                    var index = $("#quesTitle").attr("data-index");
                    $("#quesTitle").attr("data-index", (Number(index) - 1));
                })
            } else {
                $tr.nextAll().each(function () {
                    var index = $(this).find(".quesIndex").text();
                    $(this).find(".quesIndex").text(Number(index) - 1);
                })
                $tr.remove();
                var index = $("#quesTitle").attr("data-index");
                $("#quesTitle").attr("data-index", (Number(index) - 1));
            }
        });

        $("table ").on('click', ".upper", function () {
            var $tr = $(this).parent().parent();
            var curIndex = $tr.find(".quesIndex").text();
            if (curIndex == "1") {
                return false;
            }
            var $preTr = $tr.prev();
            var preIndex = $preTr.find(".quesIndex").text();
            $tr.find(".quesIndex").text(preIndex);
            $preTr.find(".quesIndex").text(curIndex);
            var preTrHtml = $tr.prev().prop("outerHTML");
            $preTr.remove();
            $tr.after(preTrHtml);
        });

        $("table ").on('click', ".down", function () {
            var index = $("#quesTitle").attr("data-index");
            var $tr = $(this).parent().parent();
            var curIndex = $tr.find(".quesIndex").text();
            if (curIndex == index) {
                return false;
            }
            var $nextTr = $tr.next();
            var nextIndex = $nextTr.find(".quesIndex").text();
            $tr.find(".quesIndex").text(nextIndex);
            $nextTr.find(".quesIndex").text(curIndex);
            var curTrHtml = $tr.prop("outerHTML");
            $tr.remove();
            $nextTr.after(curTrHtml);
            $nextTr.next().find(".down").focus();
        })

    });

    function addQuestion(questions) {
        var relatedQuestionPath = basePath + "/question/getRelatedQuestionById.json";
        var quesIds = new Array();
        for (var key = 0; key < questions.length; key++) {

            var data = questions[key];
            var index = $("#quesTitle").attr("data-index");
            index = index == "" ? 0 : index;
            var isRepeat = false;
            var id = data.id;
            var type = data.quesType;
            var quesCode = data.quesCode;

            $(".quesId").each(function () {
                if (id == $(this).val()) {
                    BootstrapDialog.alert({title: "提示", message: "该题目(" + quesCode + ")已添加，请勿重复添加"});
                    isRepeat = true;
                    return false;
                }

            })
            if (isRepeat) {
                return false;
            }
            if (type == 2) {//当为A2题型时
                //需要添加关联的题目
                $.ajax({
                    url: relatedQuestionPath,
                    type: "get",
                    data: {"id": id},
                    dataType: "json",
                    async: false,
                    success: function (r) {
                        if (r.length == 0) {
                            var data = getQuesDetail(id);
                            var str = getHtml(data, index);
                            $quesTitle = $("#quesTitle");
                            $quesTitle.parent().append(str);
                            index++;
                            $("#quesTitle").attr("data-index", index);

                            quesIds.push(data.id);
                        } else {
                            for (var key = 0; key < r.length; key++) {
                                var data = r[key];
                                if ($.inArray(data.id, quesIds) == -1) {
                                    var str = getHtml(data, index);

                                    $quesTitle = $("#quesTitle");
                                    $quesTitle.parent().append(str);
                                    index++;
                                    $("#quesTitle").attr("data-index", index);
                                    quesIds.push(data.id);
                                }

                            }
                        }

                    }
                });
            } else {
                var data = getQuesDetail(id);
                var str = getHtml(data, index);
                $quesTitle = $("#quesTitle");
                $quesTitle.parent().append(str);
                index++;
                $("#quesTitle").attr("data-index", index);

                quesIds.push(data.id);
            }
        }

        BootstrapDialog.alert("添加题目成功");
    }

    function getQuesDetail(id) {
        var questionDetailPath = basePath + "/question/getQuestionById.json";
        var data;
        $.ajax({
            url: questionDetailPath,
            type: "get",
            data: {"id": id},
            dataType: "json",
            async: false,
            success: function (r) {
                data = r;
            }
        })
        return data;
    }

    function getHtml(data, index) {
        var quesId = data.id;
        var relatedCode = data.relationCode == null ? "" : data.relationCode;
        var paperId = $("input[name='id']").val();
        var quesCode = data.quesCode;
        var stem = data.stem == null ? "" : data.stem;
        var question = data.question == null ? "" : data.question;
        var quesType = data.quesType == null ? "" : data.quesType;
        var quesTypeArray = new Array("A1型题", "A2型题", "B型题", "X型题");
        var quesTypeValue = quesTypeArray[Number(quesType) - 1];
        var options = new Array();
        if (data.optionA != null && data.optionA != '') {
            options.push(data.optionA);
        }
        if (data.optionB != null && data.optionB != '') {
            options.push(data.optionB);
        }
        if (data.optionC != null && data.optionC != '') {
            options.push(data.optionC);
        }
        if (data.optionD != null && data.optionD != '') {
            options.push(data.optionD);
        }
        if (data.optionE != null && data.optionE != '') {
            options.push(data.optionE);
        }
        if (data.optionF != null && data.optionF != '') {
            options.push(data.optionF);
        }
        var answerArray = new Array("A", "B", "C", "D", "E", "F");
        var answer = data.answer;
        var analysis = data.analysis;

        var quesHtml = "";
        if (stem == '') {
            quesHtml = '&nbsp;&nbsp;&nbsp;&nbsp;题目：' + question;
        } else {
            quesHtml = '&nbsp;&nbsp;&nbsp;&nbsp;主题干：' + question + '<br>' +
                '&nbsp;&nbsp;&nbsp;&nbsp;分题干：' + stem;
        }
        var answerHtml = "";
        for (var i = 0; i < options.length; i++) {
            answerHtml = answerHtml +
                '<div class="checkbox checkbox-success">' +
                '<label for="myAnswer[' + index + '][' + i + ']">' +
                answerArray[i] + '：' + options[i] +
                '</label>' +
                '</div>';
        }

        var str =
            '<tr class="quesDetail" data-related = "' + relatedCode + '">' +
            '<td class="col-xs-1" >' +
            '<input type="hidden" class="quesId" name="paperDetails[' + index + '].quesId" value="' + quesId + '" />' +
            '<input type="hidden" name="paperDetails[' + index + '].paperId" value="' + paperId + '" />' +
            '第 <span class="quesIndex">' + (Number(index) + 1) + '</span>题<br>' +
            quesCode + '<br>' +
            quesTypeValue +
            '</td>' +
            '<td class="col-xs-7 ">' +
            quesHtml +
            answerHtml +
            '&nbsp;&nbsp;&nbsp;&nbsp;正确答案：' + answer + '<br>' +
            '&nbsp;&nbsp;&nbsp;&nbsp;解析：' + analysis + '<br>' +
            '</td>' +
            '<td class="col-xs-1" >' +
            '<input type="text" class="form-control validate[required]" name="paperDetails[' + index + '].score" value="1" />' +
            '</td>' +
            '<td class="col-xs-3" >' +
            '<button type="button" class="btn btn-danger delete">删除</button>' +
            '<button type="button" class="btn btn-info upper">上移</button>' +
            '<button type="button" class="btn btn-info down">下移</button>' +
            '</td>' +
            '</tr>';
        return str;
    }

</script>
</body>
</html>
